import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../layout/index.vue'),
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: '首页',
        component: () => import('../views/index/index.vue')
      },
      {
        path: '/system/config',
        name: '系统设置',
        component: () => import('../views/system/config/index.vue')
      },
      {
        path: '/system/role',
        name: '角色管理',
        component: () => import('../views/system/role/index.vue')
      },
      {
        path: '/system/menu',
        name: '菜单管理',
        component: () => import('../views/system/menu/index.vue')
      },
      {
        path: '/system/user',
        name: '用户管理',
        component: () => import('../views/system/user/index.vue')
      },
      {
        path: '/tasks/dashboard',
        name: '任务统计',
        component: () => import('../views/tasks/dashboard/index.vue')
      },
      {
        path: '/tasks/task_definition',
        name: '任务定义',
        component: () => import('../views/tasks/task_definition/index.vue')
      },
      {
        path: '/tasks/tasks',
        name: '任务执行',
        component: () => import('../views/tasks/tasks/index.vue')
      },
      {
        path: '/tasks/task_result',
        name: '任务记录',
        component: () => import('../views/tasks/task_result/index.vue')
      },
      {
        path: '/system/logs',
        name: '操作日志',
        component: () => import('../views/system/logs/index.vue')
      },
      {
        path: '/userCenter',
        name: '个人中心',
        component: () => import('../views/userCenter/index.vue')
      },
      {
        path: '/testPage',
        name: '测试页面',
        component: () => import('../views/testPage/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置导航守卫
// 在访问路由前进行拦截
router.beforeEach((to, from, next) => {
  // 获取存储的token
  const token = window.sessionStorage.getItem('token')

  // 如果是登录页面，直接放行
  if (to.path === '/login') {
    next()
    return
  }

  // 如果没有token，跳转到登录页面
  if (!token) {
    next('/login')
    return
  }

  // 有token，放行
  next()
})

export default router
